package cn.desk.faq;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;

import cn.calm.commons.dao.IBaseDao;
import cn.calm.entity.Faq;
import cn.desk.faq.service.IFaqService;
import cn.desk.faq.service.impl.FaqServiceImpl;

@SuppressWarnings("rawtypes")
public class Activator implements BundleActivator {
	public static BundleContext context;
	private static Logger log = Logger.getLogger(Activator.class);

	private ServiceRegistration<IFaqService> faqServiceRegistration;
	private EntityManager em;
	private EntityManagerFactory emf;

	@Override
	public void start(BundleContext context) throws Exception {
		log.debug("starting");
		try {
			Activator.context = context;
			ServiceReference<IBaseDao> serviceRef = context
					.getServiceReference(IBaseDao.class);
			IBaseDao dao = context.getService(serviceRef);
			log.debug("dao:" + dao);
			IFaqService<Faq> userService = new FaqServiceImpl<Faq>();
			emf = Persistence.createEntityManagerFactory("entity");
			em = emf.createEntityManager();
			dao.setSession(em);
			userService.setBaseDao(dao);

			faqServiceRegistration = context.registerService(
					IFaqService.class, userService, null);
			
		} finally {
			log.debug("started");
		}
	}

	@Override
	public void stop(BundleContext arg0) throws Exception {
		Activator.context = null;
		if (faqServiceRegistration != null) {
			faqServiceRegistration.unregister();
		}
		if (em != null) {
			em.close();
		}
		if (emf != null) {
			emf.close();
		}
	}

}
